package setting

import (
	"github.com/spf13/viper"
	"path/filepath"
)

var (
	DeployType = "cluster"
)

type Application struct {
	Mode           string
	Node           int64
	Deploy         string
	HTTPAddr       string
	HTTPPort       string
	DataPath       string
	LogsPath       string
	PluginsPath    string
	HomePath       string
	StaticRootPath string
	EnabledSSL     bool
	EncryptionKey  string
	AllowedOrigins []string
	//是否进行了数据库配置
	Installed bool
}
type Paths struct {
	Data    string
	Logs    string
	Plugins string
}

func (cfg *Cfg) loadApplication(viper *viper.Viper, args CommandLineArgs) error {
	cfgApp := viper.Sub("application")
	cfg.Application = Application{
		Mode:           cfgApp.GetString("mode"),
		Node:           cfgApp.GetInt64("node"),
		Deploy:         cfgApp.GetString("deploy"),
		HTTPAddr:       cfgApp.GetString("host"),
		HTTPPort:       cfgApp.GetString("port"),
		EnabledSSL:     cfgApp.GetBool("enabledSSL"),
		EncryptionKey:  cfgApp.GetString("encryptionKey"),
		AllowedOrigins: cfgApp.GetStringSlice("allowedOrigins"),
		Installed:      cfgApp.GetBool("installed"),
	}
	cfg.BuildVersion = "v0.0.0.1"
	cfgPath := cfgApp.Sub("paths")
	cfg.Application.DataPath = cfgPath.GetString("data")
	cfg.Application.LogsPath = cfgPath.GetString("Logs")
	cfg.Application.PluginsPath = cfgPath.GetString("Plugins")
	cfg.Application.StaticRootPath = cfgPath.GetString("staticRootPath")

	//paths
	cfg.setSystemPath(viper, args)
	return nil
}
func (cfg *Cfg) setSystemPath(viper *viper.Viper, args CommandLineArgs) {

	if args.HomePage != "" {
		cfg.Application.HomePath = args.HomePage
	} else {
		var err error
		cfg.Application.HomePath, err = filepath.Abs(".")
		if err != nil {
			panic(err)
		}
	}
	paths := viper.Sub("application").Sub("paths")
	cfg.Application.DataPath = paths.GetString("data")
	cfg.Application.PluginsPath = paths.GetString("plugins")
	cfg.Application.LogsPath = paths.GetString("logs")
	if cfg.Application.DataPath == "" || cfg.Application.PluginsPath == "" || cfg.Application.LogsPath == "" {
		panic("setting datapath、pluginspath、logsPath not is value ")
	}
	return
}
